using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.ReportingServices;

using Syncfusion.Windows.Forms.Tools;

namespace ctsu.Admin.Forms
{
	public class FormReportingServices : System.Windows.Forms.Form
	{
		private string _server = "";
		private bool _bFirstLoad = true;
		private bool _bLoading;
		private TreeNodeAdv _root;
		private System.Windows.Forms.Panel pnlTop;
		private System.Windows.Forms.PictureBox pictureBox1;
		private System.Windows.Forms.Label label1;
		private Syncfusion.Windows.Forms.Tools.DockingManager dockingManager1;
		private System.Windows.Forms.Panel pnlTree;
		private Syncfusion.Windows.Forms.Tools.DockingClientPanel dockingClientPanel1;
		protected Syncfusion.Windows.Forms.Tools.TreeViewAdv tv1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.ComboBox cboFormat;
		private System.Windows.Forms.Button btnRun;
		private System.Windows.Forms.Button btnRefresh;
		private System.Windows.Forms.Label lblStatus;
		private System.Windows.Forms.ImageList imageList1;
		private System.Windows.Forms.Label lblDescription;
		private System.Windows.Forms.GroupBox gbxParams;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Button btnUpdate;
		private System.ComponentModel.IContainer components;

		delegate void AddTreeNodesDelegate(string path, ArrayList al);
		delegate void AddTreeNodeFolderDelegate(string path, string name);
		delegate void EnableBtnRefreshDelagte();

		public FormReportingServices()
		{
			InitializeComponent();
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormReportingServices));
			Syncfusion.Windows.Forms.Tools.CaptionButtonsCollection ccbpnlTree = new Syncfusion.Windows.Forms.Tools.CaptionButtonsCollection();
			Syncfusion.Windows.Forms.Tools.TreeNodeAdvStyleInfo treeNodeAdvStyleInfo1 = new Syncfusion.Windows.Forms.Tools.TreeNodeAdvStyleInfo();
			this.dockingManager1 = new Syncfusion.Windows.Forms.Tools.DockingManager(this.components);
			this.pnlTree = new System.Windows.Forms.Panel();
			this.tv1 = new Syncfusion.Windows.Forms.Tools.TreeViewAdv();
			this.imageList1 = new System.Windows.Forms.ImageList(this.components);
			this.pnlTop = new System.Windows.Forms.Panel();
			this.label1 = new System.Windows.Forms.Label();
			this.pictureBox1 = new System.Windows.Forms.PictureBox();
			this.dockingClientPanel1 = new Syncfusion.Windows.Forms.Tools.DockingClientPanel();
			this.label3 = new System.Windows.Forms.Label();
			this.btnUpdate = new System.Windows.Forms.Button();
			this.gbxParams = new System.Windows.Forms.GroupBox();
			this.lblDescription = new System.Windows.Forms.Label();
			this.lblStatus = new System.Windows.Forms.Label();
			this.label2 = new System.Windows.Forms.Label();
			this.cboFormat = new System.Windows.Forms.ComboBox();
			this.btnRun = new System.Windows.Forms.Button();
			this.btnRefresh = new System.Windows.Forms.Button();
			((System.ComponentModel.ISupportInitialize)(this.dockingManager1)).BeginInit();
			this.pnlTree.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.tv1)).BeginInit();
			this.pnlTop.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
			this.dockingClientPanel1.SuspendLayout();
			this.SuspendLayout();
			// 
			// dockingManager1
			// 
			this.dockingManager1.ActiveCaptionFont = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
			this.dockingManager1.DockLayoutStream = ((System.IO.MemoryStream)(resources.GetObject("dockingManager1.DockLayoutStream")));
			this.dockingManager1.HostControl = this;
			this.dockingManager1.InActiveCaptionFont = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
			this.dockingManager1.CaptionButtons.Add(new Syncfusion.Windows.Forms.Tools.CaptionButton(Syncfusion.Windows.Forms.Tools.CaptionButtonType.Close, "CloseButton"));
			this.dockingManager1.CaptionButtons.Add(new Syncfusion.Windows.Forms.Tools.CaptionButton(Syncfusion.Windows.Forms.Tools.CaptionButtonType.Pin, "PinButton"));
			this.dockingManager1.CaptionButtons.Add(new Syncfusion.Windows.Forms.Tools.CaptionButton(Syncfusion.Windows.Forms.Tools.CaptionButtonType.Menu, "MenuButton"));
			this.dockingManager1.CaptionButtons.Add(new Syncfusion.Windows.Forms.Tools.CaptionButton(Syncfusion.Windows.Forms.Tools.CaptionButtonType.Maximize, "MaximizeButton"));
			this.dockingManager1.CaptionButtons.Add(new Syncfusion.Windows.Forms.Tools.CaptionButton(Syncfusion.Windows.Forms.Tools.CaptionButtonType.Restore, "RestoreButton"));
			ccbpnlTree.MergeWith(this.dockingManager1.CaptionButtons, false);
			this.dockingManager1.SetCustomCaptionButtons(this.pnlTree, ccbpnlTree);
			// 
			// pnlTree
			// 
			this.pnlTree.Controls.Add(this.tv1);
			this.dockingManager1.SetEnableDocking(this.pnlTree, true);
			this.pnlTree.Location = new System.Drawing.Point(1, 19);
			this.pnlTree.Name = "pnlTree";
			this.pnlTree.Size = new System.Drawing.Size(126, 422);
			this.pnlTree.TabIndex = 1;
			// 
			// tv1
			// 
			treeNodeAdvStyleInfo1.EnsureDefaultOptionedChild = true;
			this.tv1.Dock = System.Windows.Forms.DockStyle.Fill;
			// 
			// 
			// 
			this.tv1.HelpTextControl.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.tv1.HelpTextControl.Location = new System.Drawing.Point(732, 0);
			this.tv1.HelpTextControl.Name = "helpText";
			this.tv1.HelpTextControl.Size = new System.Drawing.Size(50, 17);
			this.tv1.HelpTextControl.TabIndex = 0;
			this.tv1.HelpTextControl.Text = "help text";
			this.tv1.Location = new System.Drawing.Point(0, 0);
			this.tv1.Name = "tv1";
			this.tv1.Size = new System.Drawing.Size(126, 422);
			this.tv1.StateImageList = this.imageList1;
			this.tv1.TabIndex = 0;
			this.tv1.Text = "treeViewAdv1";
			// 
			// 
			// 
			this.tv1.ToolTipControl.BackColor = System.Drawing.SystemColors.Info;
			this.tv1.ToolTipControl.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.tv1.ToolTipControl.Location = new System.Drawing.Point(642, 0);
			this.tv1.ToolTipControl.Name = "toolTip";
			this.tv1.ToolTipControl.Size = new System.Drawing.Size(41, 17);
			this.tv1.ToolTipControl.TabIndex = 1;
			this.tv1.ToolTipControl.Text = "toolTip";
			this.tv1.AfterSelect += new System.EventHandler(this.tv1_AfterSelect);
			// 
			// imageList1
			// 
			this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
			this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
			this.imageList1.Images.SetKeyName(0, "");
			this.imageList1.Images.SetKeyName(1, "");
			this.imageList1.Images.SetKeyName(2, "");
			this.imageList1.Images.SetKeyName(3, "");
			this.imageList1.Images.SetKeyName(4, "");
			this.imageList1.Images.SetKeyName(5, "");
			this.imageList1.Images.SetKeyName(6, "");
			// 
			// pnlTop
			// 
			this.pnlTop.Controls.Add(this.label1);
			this.pnlTop.Controls.Add(this.pictureBox1);
			this.pnlTop.Dock = System.Windows.Forms.DockStyle.Top;
			this.pnlTop.Location = new System.Drawing.Point(0, 0);
			this.pnlTop.Name = "pnlTop";
			this.pnlTop.Size = new System.Drawing.Size(768, 64);
			this.pnlTop.TabIndex = 0;
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(280, 6);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(376, 56);
			this.label1.TabIndex = 1;
			this.label1.Text = resources.GetString("label1.Text");
			// 
			// pictureBox1
			// 
			this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
			this.pictureBox1.Location = new System.Drawing.Point(0, 0);
			this.pictureBox1.Name = "pictureBox1";
			this.pictureBox1.Size = new System.Drawing.Size(280, 72);
			this.pictureBox1.TabIndex = 0;
			this.pictureBox1.TabStop = false;
			// 
			// dockingClientPanel1
			// 
			this.dockingClientPanel1.Controls.Add(this.label3);
			this.dockingClientPanel1.Controls.Add(this.btnUpdate);
			this.dockingClientPanel1.Controls.Add(this.gbxParams);
			this.dockingClientPanel1.Controls.Add(this.lblDescription);
			this.dockingClientPanel1.Controls.Add(this.lblStatus);
			this.dockingClientPanel1.Controls.Add(this.label2);
			this.dockingClientPanel1.Controls.Add(this.cboFormat);
			this.dockingClientPanel1.Controls.Add(this.btnRun);
			this.dockingClientPanel1.Controls.Add(this.btnRefresh);
			this.dockingClientPanel1.Location = new System.Drawing.Point(188, 64);
			this.dockingClientPanel1.Name = "dockingClientPanel1";
			this.dockingClientPanel1.Size = new System.Drawing.Size(580, 478);
			this.dockingClientPanel1.SizeToFit = true;
			this.dockingClientPanel1.TabIndex = 3;
			// 
			// label3
			// 
			this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this.label3.Location = new System.Drawing.Point(176, 312);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(328, 72);
			this.label3.TabIndex = 21;
			this.label3.Text = "Note: Parameter changes are in affect only while this form is open.  Use \'Reporti" +
				"ng Services Manager\' to make persistent changes. (Administrators only)";
			// 
			// btnUpdate
			// 
			this.btnUpdate.Enabled = false;
			this.btnUpdate.Location = new System.Drawing.Point(8, 312);
			this.btnUpdate.Name = "btnUpdate";
			this.btnUpdate.Size = new System.Drawing.Size(160, 23);
			this.btnUpdate.TabIndex = 20;
			this.btnUpdate.Text = "Update Parameter Changes";
			this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
			// 
			// gbxParams
			// 
			this.gbxParams.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this.gbxParams.Location = new System.Drawing.Point(8, 160);
			this.gbxParams.Name = "gbxParams";
			this.gbxParams.Size = new System.Drawing.Size(568, 144);
			this.gbxParams.TabIndex = 19;
			this.gbxParams.TabStop = false;
			this.gbxParams.Text = "Report parameters";
			// 
			// lblDescription
			// 
			this.lblDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this.lblDescription.Location = new System.Drawing.Point(16, 88);
			this.lblDescription.Name = "lblDescription";
			this.lblDescription.Size = new System.Drawing.Size(560, 64);
			this.lblDescription.TabIndex = 18;
			this.lblDescription.Text = "Report description:";
			// 
			// lblStatus
			// 
			this.lblStatus.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this.lblStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
			this.lblStatus.Location = new System.Drawing.Point(152, 8);
			this.lblStatus.Name = "lblStatus";
			this.lblStatus.Size = new System.Drawing.Size(424, 48);
			this.lblStatus.TabIndex = 17;
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(96, 56);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(48, 16);
			this.label2.TabIndex = 16;
			this.label2.Text = "Format:";
			// 
			// cboFormat
			// 
			this.cboFormat.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
			this.cboFormat.Items.AddRange(new object[] {
            "HTML",
            "PDF",
            "EXCEL",
            "MHTML",
            "CSV",
            "XML"});
			this.cboFormat.Location = new System.Drawing.Point(144, 56);
			this.cboFormat.Name = "cboFormat";
			this.cboFormat.Size = new System.Drawing.Size(121, 21);
			this.cboFormat.TabIndex = 15;
			// 
			// btnRun
			// 
			this.btnRun.Enabled = false;
			this.btnRun.Location = new System.Drawing.Point(8, 56);
			this.btnRun.Name = "btnRun";
			this.btnRun.Size = new System.Drawing.Size(75, 23);
			this.btnRun.TabIndex = 14;
			this.btnRun.Text = "Run Report";
			this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
			// 
			// btnRefresh
			// 
			this.btnRefresh.Location = new System.Drawing.Point(8, 8);
			this.btnRefresh.Name = "btnRefresh";
			this.btnRefresh.Size = new System.Drawing.Size(136, 32);
			this.btnRefresh.TabIndex = 13;
			this.btnRefresh.Text = "Load / Refresh Reports";
			this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
			// 
			// FormReportingServices
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(768, 542);
			this.Controls.Add(this.dockingClientPanel1);
			this.Controls.Add(this.pnlTop);
			this.Name = "FormReportingServices";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Reporting Services";
			this.Load += new System.EventHandler(this.FormReportingServices_Load);
			((System.ComponentModel.ISupportInitialize)(this.dockingManager1)).EndInit();
			this.pnlTree.ResumeLayout(false);
			((System.ComponentModel.ISupportInitialize)(this.tv1)).EndInit();
			this.pnlTop.ResumeLayout(false);
			((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
			this.dockingClientPanel1.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		private void FormReportingServices_Load(object sender, System.EventArgs e)
		{
			string url = Properties.Settings.Default.Crema2_ReportingServices_ReportingService.ToString().Trim();
			this._server = GetServerFromUrl(url);
			StringBuilder sb = new StringBuilder();

			try
			{
				btnRefresh.Enabled = false;
				BuildTree();
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not execute web service.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this, sb.ToString(), "Web Service Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}

		}

		private void btnRefresh_Click(object sender, System.EventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			try
			{
				btnRefresh.Enabled = false;
				BuildTree();
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not execute web service.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this, sb.ToString(), "Web Service Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
		}

		delegate void ServiceGetReportsDelegate(object obj);

		private void BuildTree()
		{
			tv1.Nodes.Clear();

			//start with root node
			_root = new TreeNodeAdv("CREMA Reports");
			tv1.Nodes.Add(_root);
			_root.NodeStyle.OpenImgIndex = 3;
			_root.NodeStyle.ClosedImgIndex = 6;
			_root.Expand();
			_root.Nodes.Add(new TreeNodeAdv("Please wait, loading..."));

			ServiceGetReportsDelegate getReports = new ServiceGetReportsDelegate(ServiceGetReports);
			getReports.BeginInvoke(null, EndGetReports, getReports);


		}

		private void EnableBtnReload()
		{
			btnRefresh.Enabled = true;
		}

		private void EndGetReports(IAsyncResult ar)
		{
			// Harvest results, re-thrown exceptions and clean-up resources
			try
			{
				ServiceGetReportsDelegate getReports = (ServiceGetReportsDelegate)ar.AsyncState;
				getReports.EndInvoke(ar);
			}
			catch (Exception ex)
			{

			}
			finally
			{
				EnableBtnRefreshDelagte enblBtnDelg = new EnableBtnRefreshDelagte(EnableBtnReload);
				this.BeginInvoke(enblBtnDelg, null);
			}
		}

		private string GetServerFromUrl(string url)
		{
			int pos1 = url.IndexOf("//");
			int pos2 = url.IndexOf("/", pos1 + 2);

			string retVal = url.Substring(pos1 + 2, (pos2 - pos1) - 2);
			return retVal;
		}

		private void ServiceGetReports(object obj)
		{
			ReportingServices.ReportingService rs = new ReportingService();
			//pass your credentials to the web service

			System.Net.ICredentials credentials = new System.Net.NetworkCredential("crp-apps", "billgates", "chboston");
			rs.Credentials = credentials;//System.Net.CredentialCache.DefaultCredentials;

			//start by getting the nodes (reports only, skip folders) for the gcrc folder
			ArrayList al = ServiceGetReportsWithParams(rs, "/GCRC");

			//use a delagate to build the tree
			AddTreeNodesDelegate addTreeNodes = new AddTreeNodesDelegate(AddTreeNodes);
			this.BeginInvoke(addTreeNodes, new object[] { "CREMA Reports", al });

			ArrayList alFolders = ServiceGetFolders("/GCRC", rs);
			AddTreeNodeFolderDelegate addTreeNodeFolder = new AddTreeNodeFolderDelegate(AddTreeNodeFolder);
			foreach (string folder in alFolders)
			{
				if (folder.Contains("Investigator"))
					continue;
				if (folder.Contains("Temp"))
					continue;
				if (folder.Contains("GCRC Census"))
					continue;
				string folderName = Path.GetFileName(folder);
				this.BeginInvoke(addTreeNodeFolder, new object[] { "CREMA Reports", folderName });
				al = ServiceGetReportsWithParams(rs, folder);
				this.BeginInvoke(addTreeNodes, new object[] { "CREMA Reports\\" + folderName, al });
			}

		}

		private ArrayList ServiceGetFolders(string path, ReportingService rs)
		{
			CatalogItem[] cia = rs.ListChildren(path, true);
			ArrayList al = new ArrayList(cia.Length);
			for (int i = 0; i < cia.Length; i++)
			{
				CatalogItem cii = cia[i];
				if (cii.Type == ItemTypeEnum.Folder)
					al.Add(cii.Path);
			}
			return al;
		}

		private void AddTreeNodeFolder(string parentNodePath, string folderName)
		{
			TreeNodeAdv tnParent = tv1.GetNodeFromPath(parentNodePath);
			TreeNodeAdv tn = null;

			tn = new TreeNodeAdv(folderName);
			tnParent.Nodes.Add(tn);
			tn.NodeStyle.ClosedImgIndex = 1;
			tn.NodeStyle.OpenImgIndex = 2;

			TreeNodeAdv tn2 = new TreeNodeAdv("Please wait, loading...");
			tn.Nodes.Add(tn2);
			tn.Expand();

		}

		private void AddTreeNodes(string parentNodePath, ArrayList alReports)
		{
			TreeNodeAdv tnParent = tv1.GetNodeFromPath(parentNodePath);
			TreeNodeAdv tn = null;
			TreeNodeAdv tnParam = null;
			TreeNodeAdv tnParamValue = null;

			tn = tv1.GetNodeFromPath(parentNodePath + "\\Please wait, loading...");
			if (tn != null)
			{
				if (parentNodePath != "CREMA Reports")
					tn.Parent.CollapseAll();
				tn.Remove();
			}


			foreach (RSReport rsr in alReports)
			{
				tn = new TreeNodeAdv(rsr.Name);
				tnParent.Nodes.Add(tn);
				tn.NodeStyle.ClosedImgIndex = 0;
				tn.NodeStyle.OpenImgIndex = 0;
				tn.Tag = rsr;
				if (rsr.Parameters != null)
				{
					foreach (ReportParameter rp in rsr.Parameters)
					{
						string name = rp.Name;
						string defaultVal = "no default";
						if (rp.DefaultValues != null)
						{
							if (rp.DefaultValues[0] != null)
							{
								defaultVal = rp.DefaultValues[0].ToString();
								if (rp.Type == ParameterTypeEnum.DateTime)
									defaultVal = DateTime.Parse(defaultVal).ToShortDateString();
							}
						}

						tnParam = new TreeNodeAdv(name);
						tnParam.Tag = rp;
						tnParam.NodeStyle.ClosedImgIndex = 4;
						tnParam.NodeStyle.OpenImgIndex = 4;
						tn.Nodes.Add(tnParam);
						tnParamValue = new TreeNodeAdv(defaultVal);
						tnParamValue.NodeStyle.NoChildrenImgIndex = -1;
						tnParam.Nodes.Add(tnParamValue);
					}
				}
			}
			btnRun.Enabled = true;
		}

		private ArrayList ServiceGetReportsWithParams(ReportingService rs, string path)
		{
			ArrayList al = new ArrayList();
			CatalogItem[] cia = rs.ListChildren(path, false);
			foreach (CatalogItem cii in cia)
			{
				//only do reports
				if (cii.Type == ItemTypeEnum.Report)
				{
					RSReport rsr = new RSReport();
					rsr.Name = cii.Name;
					rsr.Path = cii.Path;
					rsr.Description = cii.Description;
					rsr.Parameters = ServiceGetParameters(rs, cii.Path);

					al.Add(rsr);
				}
			}
			return al;
		}

		private ArrayList ServiceGetParameters(ReportingService rs, string path)
		{
			string hist = null;
			bool forRend = true;
			ParameterValue[] paraVals = null;
			DataSourceCredentials[] dsc = null;
			ArrayList al = new ArrayList();
			ReportParameter[] aParams = null;
			aParams = rs.GetReportParameters(path, hist, forRend, paraVals, dsc);
			if (aParams != null)
			{
				foreach (ReportParameter rp in aParams)
					al.Add(rp);
			}
			return al;
		}

		private void btnRun_Click(object sender, System.EventArgs e)
		{
			StringBuilder sb = new StringBuilder("http://" + _server + "/reportserver?");
			StringBuilder msg = new StringBuilder();
			TreeNodeAdv t = tv1.SelectedNode;

			if (t == null)
				return;

			object obj = t.Tag;
			if (obj == null)
				return;

			if (btnUpdate.Enabled)
			{
				msg.Append("Parameters were not updated.");
				msg.Append(Environment.NewLine);
				msg.Append("Do you want to continue?");
				if (MessageBox.Show(this, msg.ToString(), "Parameters Not Updated", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
					return;
			}

			RSReport rsr = obj as RSReport;
			if (rsr != null)
			{
				Console.WriteLine("   CatalogItem");
				sb.Append(rsr.Path + "&rs:Command=Render");
				if (cboFormat.SelectedIndex > 0)
					sb.Append("&rs:Format=" + cboFormat.Text);
				GetUrlParameters(sb, t);

				System.Diagnostics.Process.Start(sb.ToString());
			}
			else
				Console.WriteLine("   ReportParameter");
		}

		private void btnUpdate_Click(object sender, System.EventArgs e)
		{
			btnUpdate.Enabled = false;
			DateTimePickerAdv dt;
			string sVal = "";
			//get parameter controls
			foreach (Control ctl in gbxParams.Controls)
			{
				if (ctl.Name.IndexOf("p_aram") > -1)
				{
					TreeNodeAdv child = (TreeNodeAdv)ctl.Tag;
					ReportParameter rp = (ReportParameter)child.Tag;
					if (rp.Type == ParameterTypeEnum.DateTime)
					{
						dt = (DateTimePickerAdv)ctl;
						sVal = dt.Value.ToShortDateString();
					}
					else
						sVal = ctl.Text;

					TreeNodeAdv paraValNode = child.Nodes[0];
					paraValNode.Text = sVal;
					Console.WriteLine("Parameter: " + child.Text);
					Console.WriteLine("  Value: " + sVal);
				}
			}
		}

		private void tv1_AfterSelect(object sender, System.EventArgs e)
		{
			_bLoading = true;
			//Clear Parameter controls
			ClearParameterControls();
			int count = 0;
			int y = 24;
			int x = 8;

			btnRun.Enabled = false;
			btnUpdate.Enabled = false;
			lblDescription.Text = "Report description: ";
			TreeNodeAdv t = tv1.SelectedNode;
			if (t == null)
				return;

			if (t.Tag == null)
				return;

			RSReport rsr = t.Tag as RSReport;
			if (rsr == null)
				return;

			if (rsr != null)
			{
				Console.WriteLine("   CatalogItem");
				lblDescription.Text = "Report description: " + rsr.Description;
				btnRun.Enabled = true;

				if (t.HasChildren)
				{
					foreach (TreeNodeAdv child in t.Nodes)
					{
						count++;
						if (count > 1)
						{
							y += 32;
						}
						ReportParameter rp = (ReportParameter)child.Tag;
						Label lbl = new Label();
						lbl.Name = "lblPrompt" + count.ToString();
						lbl.Text = rp.Prompt + ": ";
						lbl.AutoSize = true;
						lbl.Location = new Point(x, y);
						lbl.Parent = this.gbxParams;
						lbl.Visible = true;
						Console.WriteLine("Parameter: " + rp.Name);
						if (rp.Type == ParameterTypeEnum.DateTime)
						{
							DateTimePickerAdv dt = new DateTimePickerAdv();
							dt.Width = 88;
							dt.Format = DateTimePickerFormat.Short;
							dt.ShowCheckBox = false;
							dt.Left = lbl.Left + lbl.Width + 10;
							dt.Top = y;
							dt.Parent = this.gbxParams;
							dt.Visible = true;
							dt.ValueChanged += new EventHandler(param_ValueChanged);
							dt.Tag = child;
							dt.Name = "p_aram" + count.ToString();

							if (rp.DefaultValues == null)
								dt.Value = DateTime.Today;
							else
								dt.Value = DateTime.Parse(rp.DefaultValues[0]);
						}
						else
						{
							TextBox txt = new TextBox();
							txt.Width = 200;
							txt.Left = lbl.Left + lbl.Width + 10;
							txt.Top = y;
							txt.Parent = this.gbxParams;
							txt.Visible = true;
							txt.TextChanged += new EventHandler(param_ValueChanged);
							//TODO - do something with keypress if type is numeric
							txt.Tag = child;
							txt.Name = "p_aram" + count.ToString();

							if (rp.DefaultValues != null)
								txt.Text = rp.DefaultValues[0].ToString();
						}
					}
				}
			}
			_bLoading = false;
		}

		private void GetUrlParameters(StringBuilder sb, TreeNodeAdv t)
		{
			//TODO - more exstensive validations on parameter values
			TreeNodeAdv valNode = null;
			ReportParameter rp = null;
			if (!t.HasChildren)
				return;

			foreach (TreeNodeAdv child in t.Nodes)
			{
				//check for a value node
				if (child.HasChildren)
				{
					valNode = child.Nodes[0];
					if (valNode.Text == "no default")
						continue;
					if (valNode.Text.Length == 0)
						continue;
					rp = (ReportParameter)child.Tag;
					sb.Append("&" + rp.Name + "=" + valNode.Text);
				}
			}
		}

		private void ClearParameterControls()
		{
			gbxParams.Controls.Clear();
		}

		private void param_ValueChanged(object sender, EventArgs e)
		{
			if (_bLoading)
				return;
			btnUpdate.Enabled = true;
		}
	}

	public class RSReport
	{
		private string _name;
		private string _path;
		private string _description;
		ArrayList _alParams;
		public RSReport()
		{ }

		public string Name
		{
			get { return _name; }
			set { _name = value; }

		}
		public string Path
		{
			get { return _path; }
			set { _path = value; }

		}

		public string Description
		{
			get { return _description; }
			set { _description = value; }

		}

		public ArrayList Parameters
		{
			get { return _alParams; }
			set { _alParams = value; }
		}

	}

	public class RSReportParameter
	{
		string _name;
		string _value;
		ParameterTypeEnum _type;

		public RSReportParameter()
		{ }

		public string Name
		{
			get { return _name; }
			set { _name = value; }

		}
		public string Value
		{
			get { return _value; }
			set { _value = value; }

		}

		public ParameterTypeEnum Parameter
		{
			get { return _type; }
			set { _type = value; }
		}
	}
}
